//积分商城
const app = getApp()
var server = require('../../utils/server');
var common = require('../../utils/common');
var amapFile = require('../../libs/amap-wx.js');
Page({
  data: {
    page: 1,
    list: [],
    poptype: 3,
    showPhonePop: false,
    showLoginPop: false,
    userInfo: {},
    errmsg: "",
    isLocate: true,
    isEmpty: false,
    isCanExchange: true,
    amount: "",
    curTab: 0,
    ticketsnum: '',
    isLogin: true,
    storeId: '',
    isCanAdd: true,
    curGoodsId: '',
    isHasStoreArea: true,
    isDisableLog: false,
    isDisableReg: false,
    loadMore:false
  },
  onLoad: function (options) {
    this.setData({
      curTab: options.scene == undefined ? 0 : options.scene
    })
  },
  onShow: function () {
    this.data.page = 1;
    this.setData({
      isLocate: app.globalData.isLocate
    })
    if (this.data.isLocate) {
      this.getComponyId();
    } else {
      console.log(221)
    }
  },
  onHide() {
    this.setData({
      poptype: 3
    })
  },
  getUserInfo() {
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        this.data.tel = res.data.member.cellphone;
        this.data.userInfo = res.data;
        console.log(this.data.userInfo)
        this.setData({
          ticketsnum: res.data.coupon_num
        })
        this.getScoreCardNum(res.data.member.cellphone)
        this.getVouchers();
      },
      fail: res => {
        this.checkRegister();
      }
    })
  },
  getComponyId() {
    if (app.globalData.latitude == null || app.globalData.longitude == null || app.globalData.city == "") {
      this.locateCur();
      console.log(12)
    } else {
      wx.getStorage({
        key: 'userInfo',
        success: res => {
          this.data.userInfo = res.data;
          this.data.tel = res.data.member.cellphone;
          this.setData({
            ticketsnum: res.data.coupon_num
          })
          wx.getStorage({
            key: 'storeId',
            success: resp => {
              this.getScoreCardNum(res.data.member.cellphone)
              this.getVouchers();
            },
            fail: res => {
              this.getListByLaLon(app.globalData.latitude, app.globalData.longitude, app.globalData.city)
            }
          })
        },
        fail: resp => {
          this.checkRegister();
        }
      })
    }
  },
  //重新定位获取经纬度
  locateCur() {
    var gdMap = new amapFile.AMapWX({
      key: common.gdKey
    });
    gdMap.getRegeo({
      success: res => {
        console.log(res)
        app.globalData.location = res[0].regeocodeData.pois[0] == undefined ? res[0].name : res[0].regeocodeData.pois[0].name;
        app.globalData.longitude = res[0].longitude;
        app.globalData.latitude = res[0].latitude;
        app.globalData.city = res[0].regeocodeData.addressComponent.city;
        app.globalData.locateCity = res[0].regeocodeData.addressComponent.city;
        app.globalData.locateProvince = res[0].regeocodeData.addressComponent.province;
        this.getListByLaLon(res[0].latitude, res[0].longitude, app.globalData.city);
        app.globalData.addrId = null;
      },
      fail: info => {
        console.log('fail')
        this.setData({
          isLocate: false
        })
        app.globalData.isLocate = false
      }
    })
  },
  getListByLaLon(la, lon) {
    var returntype = "one";
    common.getStoreByLaLon(lon, la, returntype, app.globalData.city, "").then(res => {
      if (JSON.stringify(res.data) == "{}") {
        this.getUserInfo();
      } else if (JSON.stringify(res.data) != "{}" && res.errno == '0') {
        wx.setStorage({
          key: 'storeId',
          data: res.data.store_id,
          success: res => {
            this.getUserInfo();
          }
        })

      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  getScoreCardNum(tel) {
    server.postJSON(common.basePath + 'membercard/getscorecard', {
      "mobile": tel,
      "city": app.globalData.city
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          scoreNum: res.data.data.score,
          isHasStoreArea: res.data.data.company_id > 0 ? true : false
        })
        var that = this;
        if (res.data.data.company_id == 0) {
          wx.removeStorage({
            key: 'storeId',
            success: function (res) {
              that.getVouchers();
            },
          })
        }
      }
    })
  },
  checkRegister() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          console.log('未登录')
          this.setData({
            isLogin: false
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          this.data.tel = res.data.member.cellphone;
          this.setData({
            ticketsnum: res.data.coupon_num,
            avatar: res.data.avatar
          })
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          this.setData({
            showPhonePop: false,
            showLoginPop: false,
            isLogin: true
          })
          wx.getStorage({
            key: 'storeId',
            success: resp => {
              this.getVouchers();
            },
            fail: res => {
              this.getListByLaLon(app.globalData.latitude, app.globalData.longitude, app.globalData.city)
            }
          })
          this.getScoreCardNum(res.data.member.cellphone);
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          isLogin: false
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  showCheckTel() {
    this.setData({
      showPhonePop: false
    })
    wx.navigateTo({
      url: '../common/register',
    })
  },
  getPhoneNumber: function (e) {
    var that = this;
    this.setData({
      isDisableReg: true
    })
    if (e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        icon: 'none',
        title: '需要授权手机号后使用元初到家！',
      })
      this.setData({
        isDisableReg: false
      })
    } else {
      var that = this;
      wx.login({
        success: res => {
          this.setData({
            showPhonePop: false
          });
          server.postJSON(common.basePath + 'miniprogram/registermember/', {
            "iv": e.detail.iv,
            "encryptedData": e.detail.encryptedData,
            "js_code": res.code
          }, res => {
            if (res.data.errno == '0') {
              that.setData({
                tel: res.data.data.member.cellphone,
                ticketsnum: res.data.data.coupon_num,
                isLogin: true,
                isDisableReg: false
              })
              wx.getStorage({
                key: 'storeId',
                success: resp => {
                  that.getVouchers();
                },
                fail: res => {
                  that.getListByLaLon(app.globalData.latitude, app.globalData.longitude, app.globalData.city)
                }
              })
              that.getScoreCardNum(res.data.data.member.cellphone);
              that.storageUserinfo(res.data.data)
            } else {
              this.setData({
                isDisableReg: false
              })
              common.showErrorToast(res.data.errmsg);
            }
          })
        },
        fail: res => {
          this.setData({
            isDisableReg: false
          })
        }
      })
    }
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isLogin: true,
        isDisableLog: false
      })
      this.checkRegister();
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  goToTicketDetail(e) {
    wx.navigateTo({
      url: 'vouchersDetail?ticketid=' + e.currentTarget.dataset.id,
    })
  },
  showConfirmCont(e) {
    var curtarget = e.currentTarget.dataset;
    this.setData({
      ['list[' + curtarget.index + '].isCanGet']: false,
    })
    server.postJSON(common.storePath + 'coupon/isexchange/', {
      "score_mall_id": curtarget.id
    }, res => {
      this.setData({
        ['list[' + curtarget.index + '].isCanGet']: true,
      })
      if (res.data.errno == '0') {
        this.data.curCouponId = curtarget.id;
        console.log(curtarget.couponparams)
        this.setData({
          poptype: 0,
          couponScoreNum: curtarget.scorenum,
          amount: curtarget.amount,
          curGoodsId: curtarget.goodsid,
          title: curtarget.title,
          retailprice: curtarget.retailprice,
          couponparams: curtarget.couponparams,
          oldprice: curtarget.oldprice
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
    console.log(this.data.poptype)
  },
  goToTickets() {
    wx.navigateTo({
      url: 'userVouchers',
    })
  },
  goToMemberCardIndex() {
    wx.navigateTo({
      url: '../memberCard/memberCardIndex',
    })
  },
  getVouchers() {
    common.showLoading();
    var storeid = wx.getStorageSync('storeId');
    this.data.storeId = storeid;
    console.log(storeid, 'storeid')
    server.postJSON(common.storePath + 'coupon/scoremalllist/', {
      "page": this.data.page,
      "pageSize": 20,
      "store_id": storeid,
      "is_full_exchange": this.data.curTab
    }, res => {
      common.hideLoading();
      if (res.data.errno == '0') {
        var new_coupon_list = [];
        for (var i = 0; i < res.data.data.length; i++) {
          res.data.data[i].isCanGet = true;
          new_coupon_list.push(res.data.data[i]);
        }

        this.setData({
          list: new_coupon_list,
          isEmpty: res.data.data.length > 0 ? false : true,
          isLogin: true,
          loadMore:res.data.data.length>=20?true:false
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //滚动到底部触发事件  
  onReachBottom() {
    console.log(this.data.page)
    let that = this;
    if (this.data.loadMore) {
      common.showLoading();
      common.hideLoading();
      that.data.page = that.data.page + 1;
      that.getMoreData()
    }
  },
  getMoreData() {
    server.postJSON(common.storePath + 'coupon/scoremalllist/', {
      "page": this.data.page,
      "pageSize": 20,
      "store_id": this.data.storeId,
      "is_full_exchange": this.data.curTab
    }, res => {
      console.log(res)
      if (res.data.errno == "0") {
        common.hideLoading();
        if (res.data.data.length > 0) {
          console.log(res.data.data)
          var newData = this.data.list;
          newData = newData.concat(res.data.data);
          for (var i = 0; i < newData.length; i++) {
            newData[i].isCanGet = true;
          }
          this.setData({
            list: newData,
            loadMore:res.data.data.length>=20?true:false
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  exchangeGoods() {
    this.setData({
      isCanExchange: false
    })
    var param = {
      "score_mall_id": this.data.curCouponId
    }
    this.confirmExchangeTicket(param);
  },
  getcoupon(params){
    console.log(222)
    this.setData({
      isCanExchange: false
    })
    var param = {
      "score_mall_id": this.data.curCouponId,
      "send_coupon_result": params.detail.send_coupon_result
    }
    this.confirmExchangeTicket(param);
  },
  confirmExchangeTicket(param) {
    console.log(param.send_coupon_result)
    server.postJSON(common.storePath + 'coupon/scoremallexchange/', param, res => {
      if (res.data.errno == '0') {
        if(param.send_coupon_result!=undefined||param.send_coupon_result!=''){
          this.getVouchers();
        }
        this.setData({
          poptype: 2,
          isCanExchange: true,
          ticketsnum: parseInt(this.data.ticketsnum) + 1
        })
        this.data.userInfo.coupon_num = this.data.ticketsnum;
        this.storageUserinfo(this.data.userInfo)
        this.getScoreCardNum(this.data.tel)
      } else {
        common.showErrorToast(res.data.errmsg);
        this.setData({
          isCanExchange: true
        })
      }
    })
  },
  hideCouponPop() {
    this.setData({
      poptype: 3
    })
  },
  useCoupon() {
    this.setData({
      isCanAdd: false
    })
    server.postJSON(common.storePath + 'cart/addgoods/', {
      "store_id": this.data.storeId,
      "goods_id": this.data.curGoodsId,
      "trace_id": '',
      "scene": ''
    }, res => {
      if (res.data.errno == "0") {
        common.showErrorToast("添加成功");
        this.setData({
          isCanAdd: true,
          poptype: 3
        })
      } else {
        this.setData({
          isCanAdd: true
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  switchTab(e) {
    this.setData({
      curTab: e.currentTarget.dataset.id,
    })
    this.data.page = 1;
    this.getVouchers();
  },
  goMemberScoreDetail() {
    wx.navigateTo({
      url: '../memberCard/memberScoreDetail?tel=' + this.data.tel,
    })
  },
  showLoginPop() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          this.setData({
            showPhonePop: true
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          this.setData({
            tel: res.data.member.cellphone,
            ticketsnum: res.data.coupon_num,
            avatar: res.data.avatar
          })
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          this.setData({
            showPhonePop: false,
            showLoginPop: false,
            isLogin: true
          })
          this.getVouchers();
          this.getScoreCardNum(res.data.member.cellphone);
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          showLoginPop: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false,
      isLogin: false
    })
  },
  hidePhonePop() {
    this.setData({
      showPhonePop: false,
      isLogin: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../common/agreement',
    })
  },
  goToProductsIndex() {
    app.globalData.skipType = 2;
    this.setData({
      poptype: 3
    })
    wx.navigateTo({
      url: '../shop/productsListIndex',
    })

  }
})